<?php


namespace app\business\controller;

use app\business\model\Business;
use app\business\model\CommodityAppraises;
use app\business\model\Order;
use app\business\model\OrderCommodity;
use app\business\validate\CommodityValidate;
use app\common\Upload;
use app\business\model\Commodity;
use app\business\model\CommodityClass;
use app\business\validate\BusinessValidator;
use app\common\Base;
use think\Exception;
use think\Request;
use function GuzzleHttp\Psr7\try_fopen;

/**
 * Class BusinessPage   商家信息
 * @package app\business\controller
 */
class BusinessPage extends  Base
{
    /**
     * @reply   商家回复评论
     * @param Request $request
     * @param BusinessValidator $businessValidator
     * @param CommodityAppraises $commodityAppraises
     * @return \think\response\Json
     * @throws Exception
     */
    public function reply(Request $request,CommodityAppraises $commodityAppraises,Order $order){
        try {
            $reply = $request->post('reply');
            if (preg_match('/^[A-Za-z0-9]+$/',$reply)){
                return responseJson(Base::FAIL,'请输入正确的格式');
            }elseif (mb_strlen($reply) > 100 | mb_strlen($reply) <= 0){
                return responseJson(Base::FAIL,'请输入正确的长度');
            }
            $orderId = $request->post('orderId');
            if (!$commodityAppraises->reply($reply,$orderId)){
                return responseJson(Base::FAIL,'回复评论失败，请重试');
            }
            return responseJson(Base::OK,'回复评论成功，请刷新');
        }catch (Exception $e){
            throw $e;
        }
    }
    /**
     * @allOrders   商家-订单类型（全部订单，待接单，待发货，已发货）
     * @param Order $order
     * @param OrderCommodity $orderCommodity
     * @return \think\response\Json
     */
    public function allOrders(Request $request,Order $order,OrderCommodity $orderCommodity){
        try {
            $deliveryStatus = $request->post('deliveryStatus'); //-1：待接单 0:待发货 1:已发货 2:全部
            if ($deliveryStatus == 2)$deliveryStatus = '';

            $arr = $request->cacheInfo;

            if ($deliveryStatus == ''){
                $ordersData = json_decode($order->allOrders($arr['id']),true);
            }else{
                $ordersData = json_decode($order->otherOrders($arr['id'],$deliveryStatus),true);
            }
            if (!$ordersData) {
                return responseJson(Base::OK,'暂无订单');
            }
            if (empty($ordersData)) return responseJson(Base::OK,'暂无订单数据');

            foreach ($ordersData as $key => $value){
                $ordersData[$key]['createTime'] = date('Y-m-d',$ordersData[$key]['createTime']);
                $address = $ordersData[$key]['provide'].$ordersData[$key]['city'].$ordersData[$key]['county'].$ordersData[$key]['street'].$ordersData[$key]['detail'];
                unset($ordersData[$key]['provide'],$ordersData[$key]['city'],$ordersData[$key]['county'],$ordersData[$key]['street'],$ordersData[$key]['detail']);
                $ordersData[$key]['address'] = $address;
                if (empty($commodityName = json_decode($orderCommodity->findCommodityName($ordersData[$key]['orderNum']),true))) {
                    return responseJson(Base::FAIL,'数据获取错误，请重试');
                }
                if (count($commodityName) > 1){
                    $result = '';
                    foreach ($commodityName as $k => $val){
                        $result .= $commodityName[$k]['commodityName'] . "+";
                    }
                    $result = substr($result,0,strlen($result)-1);
                    $ordersData[$key]['commodityName'] = $result;
                }else{
                    $ordersData[$key]['commodityName'] = $commodityName[0]['commodityName'];
                }

            }
            return responseJson(Base::OK,'订单数据',$ordersData);
        }catch (Exception $e){
            throw $e;
        }
    }

    /**
     * @updateOrderStatus   商家修改订单状态
     * @param Request $request
     * @param Order $order
     * @return \think\response\Json
     * @throws Exception
     */
    public function updateOrderStatus(Request $request,Order $order){
        try {
            $orderNum = $request->post('orderNum');
            $businessData = $request->cacheInfo;
            //待接单-1 待发货0 已发货1
            $deliveryStatus = $request->post('deliveryStatus');
            if (!$order->updateOrderStatus($orderNum,$businessData['id'],$deliveryStatus)){
                return responseJson(Base::FAIL,'数据修改失败，请重试');
            }
            return responseJson(Base::OK,'数据修改成功');
        }catch (Exception $e){
            throw $e;
        }
    }
    
    /**
     * @evaluationManagement    商家-评价管理（已回复，待回复，全部）
     * @param CommodityAppraises $commodityAppraises
     * @param Order $order
     * @param Commodity $commodity
     * @return \think\response\Json
     */
    public function evaluationManagement(Request $request,CommodityAppraises $commodityAppraises,Order $order,Commodity $commodity){
        try {
            $evaluationStatus = $request->post('evaluationStatus'); //0：已回复 1：待回复 2：全部
            if ($evaluationStatus == 2)$evaluationStatus = '';
            $arr = $request->cacheInfo;
            if ($evaluationStatus == ''){
                $oldEvaluation = $commodityAppraises->evaluationAll($arr['id'],$evaluationStatus);
            }else{
                $oldEvaluation = $commodityAppraises->evaluation($arr['id'],$evaluationStatus);
            }
            if ($oldEvaluation->isEmpty()){
                return responseJson(Base::OK,'暂无评论');
            }
            foreach ($oldEvaluation as $key => $value){
                if (empty($commodityName = $commodity->findCommodityName($oldEvaluation[$key]['businessId'],$oldEvaluation[$key]['commodityId']))) {
                    return responseJson(Base::FAIL,'数据获取失败，请重试');
                }
                $oldEvaluation[$key]['commodityName'] = $commodityName['commodityName'];
            }
            $oldEvaluation = json_decode($oldEvaluation,true);
            for ($i=0;$i<count($oldEvaluation);$i++){
                for ($j=$i+1;$j<count($oldEvaluation);$j++){
                    if ($oldEvaluation[$i]['orderId'] == $oldEvaluation[$j]['orderId']){
                        $oldEvaluation[$i]['commodityName'] .= "+".$oldEvaluation[$j]['commodityName'] ;
                    }
                }
            }
            $evaluation = $this->assoc_unique($oldEvaluation,'orderId');
            foreach ($evaluation as $key => $value){
                $evaluation[$key]['evaluation'] = ceil(($evaluation[$key]['commodityScore']+$evaluation[$key]['serviceScore']+$evaluation[$key]['timeScore'])/3);
                unset($evaluation[$key]['commodityScore'],$evaluation[$key]['serviceScore'],$evaluation[$key]['timeScore']);
                if (empty($createTime = $order->createTime($evaluation[$key]['orderId']))) {
                    return responseJson(Base::FAIL,'暂无评论');
                }
                $evaluation[$key]['createTime'] = date('Y-m-d',$createTime['createTime']);
                if (empty($orderStatus = $order->findOrderStatus($evaluation[$key]['orderId']))) {
                    return responseJson(Base::FAIL,'暂无评论');
                }
                switch ($orderStatus) {
                    case $orderStatus = 1:
                        $orderStatus = '配送中';
                        break;
                    case $orderStatus = 2:
                        $orderStatus = '确认收货';
                        break;
                    case $orderStatus = -1:
                        $orderStatus = '待接单';
                        break;
                    default :
                        $orderStatus = '未付款';
                        break;
                }
                $evaluation[$key]['orderStatus'] = $orderStatus;
                if ($evaluation[$key]['evaluationStatus'] == 0){
                    $evaluation[$key]['evaluationStatus'] = 'replied';          //replied
                }else{
                    $evaluation[$key]['evaluationStatus'] = 'toBeReplied';      //toBeReplied
                }
            }
            return responseJson(Base::OK,'数据获取成功',$evaluation);
        }catch (Exception $e){
            throw $e;
        }
    }
    /**
     * @commoditySearch 商家-商品搜索
     * @param Request $request
     * @param CommodityValidate $commodityValidate
     * @param Commodity $commodity
     * @param CommodityClass $commodityClass
     * @return \think\response\Json
     * @throws Exception
     */
    public function commoditySearch(Request $request,CommodityValidate $commodityValidate,Commodity $commodity,CommodityClass $commodityClass){
        try {
            if (!$commodityValidate->check($request->post())){
                return responseJson(Base::FAIL,$commodityValidate->getError());
            }
            $commodityName = $request->post('commodityName');
            $arr = $request->cacheInfo;
            if ($commodityName == ''){
                if (!$data = $commodity->commodityAllSearch($arr['id'])){
                    return responseJson(Base::FAIL,'数据获取失败');
                }
            }else{
                if (!$data = $commodity->commoditySearch($arr['id'],$commodityName)) {
                    return responseJson(Base::FAIL,'数据获取失败');
                }
            }
            foreach ($data as $key => $val){
                $catName = $commodityClass->findClassificationName($data[$key]['businessId'],$data[$key]['catId']);
                $data[$key]['catName'] = $catName['catName'];
                $data[$key]['createTime'] = date('Y-m-d',$data[$key]['createTime']);
            }
            return responseJson(Base::OK,'数据获取成功',$data);
        }catch (Exception $e){
            throw $e;
        }
    }

    /**
     * @commodityInfo 商家-商品信息管理
     * @param Commodity $commodity
     * @param CommodityClass $commodityClass
     * @return \think\response\Json
     * @throws Exception
     */
    public function commodityInfo(Request $request,Commodity $commodity,CommodityClass $commodityClass){
        try {
            $arr = $request->cacheInfo;
            if (!$data = $commodity->showCommodity($arr['id'])) {
                return responseJson(Base::FAIL,'数据获取失败，请重试');
            }
            if ($data->isEmpty()){
                return responseJson(Base::OK,'暂无商品数据');
            }
            foreach ($data as $key => $value){
                $classification = $commodityClass->classification($data[$key]['catId']);
                $data[$key]['catName'] = $classification;
                unset($data[$key]['catId']);
                $data[$key]['createTime'] = date('Y-m-d',$data[$key]['createTime']);
            }
            return responseJson(Base::OK,'数据获取成功',$data);
        }catch (Exception $e){
            throw $e;
        }
    }
    
    /**
     * @shelves 商品上架或下架
     * @param Request $request
     * @param Commodity $commodity
     * @return \think\response\Json
     * @throws Exception
     */
    public function shelves(Request $request,Commodity $commodity){
        try {
            $commodityId = $request->post('commodityId');
            $businessData = $request->cacheInfo;
            $businessId = $businessData['id'];
            $isSale = $request->post('isSale');
            if (!$commodity->updateCommodityShelves($commodityId,$businessId,$isSale)){
                return responseJson(Base::FAIL,'修改失败，请重试');
            }
            return responseJson(Base::OK,'修改成功');
        }catch (Exception $e){
            throw $e;
        }
    }

    /**
     * @recommended 商品推荐
     * @param Request $request
     * @param Commodity $commodity
     * @return \think\response\Json
     * @throws Exception
     */
    public function recommended(Request $request,Commodity $commodity){
        try {
            $commodityId = $request->post('commodityId');
            $businessData = $request->cacheInfo;
            $businessId = $businessData['id'];
            $recommended = $request->post('recommended');
            if (!$commodity->recommended($commodityId,$businessId,$recommended)){
                return responseJson(Base::FAIL,'修改失败，请重试');
            }
            return responseJson(Base::OK,'修改成功');
        }catch (Exception $e){
            throw $e;
        }
    }

    /**
     * @delCommodity    商品删除
     * @param Request $request
     * @param Commodity $commodity
     * @return \think\response\Json
     * @throws Exception
     */
    public function delCommodity(Request $request,Commodity $commodity){
        try {
            $commodityId = $request->post('commodityId');
            $businessData = $request->cacheInfo;
            $businessId = $businessData['id'];
            $deleted = $request->post('deleted');
            if (!$commodity->delCommodity($commodityId,$businessId,$deleted)){
                return responseJson(Base::FAIL,'删除失败，请重试');
            }
            return responseJson(Base::OK,'删除成功');
        }catch (Exception $e){
            throw $e;
        }
    }
    //列出商品类型  成功

    /**
     * @param Request $request
     * @param CommodityClass $commodityClass
     * @param BusinessValidator $businessValidator
     * @return \think\response\Json
     * @throws Exception
     */
    public  function  selClass(Request $request ,Business $business,CommodityClass $commodityClass,Commodity $commodity){
        // TODO 将获取缓存信息放在中间件里，请使用try catch，代码缩进不规范
        $arr = $request->cacheInfo;
        $businessId = $arr["id"];//获取商家id

        $classtext =json_decode($commodityClass ->classSel($businessId),true);

        try{
            for ($i=0;$i<count($classtext);$i++){
                $classid = $classtext[$i]['id'];
                $classupdate = $classtext[$i]['updateTime'];
                $update =substr(date("Y-m-d H:i:s",$classupdate),0,10);
                $num = count(json_decode($commodity->findclasscom($businessId,$classid),true));
                $classtext[$i]['num']=$num;
                $classtext[$i]['updateTime']=$update;
            }
        return  responseJson(Base::OK,'列出成功',$classtext);
        }catch(Exception $e){
            throw  $e;
        }

    }

    /**
     * @param Request $request
     * @param Commodity $commodity
     * @param CommodityClass $commodityClass
     * @param BusinessValidator $businessValidator
     * @return \think\response\Json
     * @throws Exception
     */
    //添加商品 成功
    public  function  addCommodity(Request $request,Business $business,Commodity $commodity ,CommodityClass $commodityClass ,BusinessValidator $businessValidator){

        // TODO 将获取缓存信息放在中间件里
        $arr = $request->cacheInfo;
        $businessId = $arr["id"];//获取商家id

        $name = $request ->post('name'); //商品名
        $typeId = $request ->post('typeId'); //商品类型
        $price = $request ->post('price'); //价格
        $desc = $request ->post('desc'); //介绍
        $img = $request ->file('img')->getInfo(); //图片路径
        $filename = $name. time(). ".png";
        $upload = new Upload();

        //上传
        if(!$upload ->upload($img['tmp_name'],$filename,'commodity')){
            return  responseJson(Base::FAIL,'添加图片失败');
        }
        try{
            if ($businessValidator -> check ($request ->post())){
                return responseJson( Base::FAIL,$businessValidator->getError());
            }
            if(!$commodity ->commodityData($name,$filename,$price,$desc,$businessId,$typeId)){
               return responseJson(Base::FAIL,'添加失败');
            }
           return responseJson(Base::JUMP_PAGE,'添加商品成功');
        }catch (Exception $e){
            throw $e;
        }

    }

    /**
     * @param Request $request
     * @param Commodity $commodity
     * @param CommodityClass $commodityClass
     * @return \think\response\Json
     * @throws \Exception
     */
    public function infoCommodity(Request $request,Commodity $commodity,BusinessValidator $businessValidator){
        // 使用try catch
        $commodityId = $request->post('cId');
        $name = $request ->post('name'); //商品名
        $typeId = $request ->post('typeId'); //商品类型
        $price = $request ->post('price'); //价格
        $desc = $request ->post('desc'); //介绍
        $imgfile= $request ->file('img'); //图片路径
        try{
            if($imgfile!=''){
                $img = $imgfile->getInfo();
                $filename = $name. time(). ".png";
                $upload = new Upload();
                //上传
                if ($businessValidator -> check ($request ->post())){
                    return responseJson( Base::FAIL,$businessValidator->getError());
                }
                if(!$upload ->upload($img['tmp_name'],$filename)){
                    return  responseJson(Base::FAIL,'添加图片失败');
                }
                if(!$commodity->updataComimg( $commodityId,$filename)){
                    return responseJson(Base::FAIL,'失败');
                }
            }
            if(!$commodity->updataCommodity( $commodityId, $typeId, $price, $name , $desc)){
                return responseJson(Base::FAIL,'失败');
            }
            return responseJson(Base::OK,'成功');
        }catch (Exception $e){
            throw $e;
        }
    }


    /**
     * @param Request $request
     * @param CommodityClass $commodityClass
     * @param BusinessValidator $businessValidator
     * @return \think\response\Json
     * @throws Exception
     */
    //添加商品类型 成功
    public  function addComclass(Request $request ,Business $business, CommodityClass $commodityClass , BusinessValidator $businessValidator){
        $type = $request ->post('type'); //商品类型

        // TODO 将获取缓存信息放在中间件里
        $arr = $request->cacheInfo;
        $businessId = $arr["id"];//获取商家id
        
        try{
            if($businessValidator ->check($request ->post())){
                return responseJson(Base::FAIL,$businessValidator->getError());
            }
            $data = $commodityClass ->classData($type,$businessId);
            if (!$data){
                return responseJson(Base::FAIL,'添加错误');
            }
                return  responseJson(Base::OK,'添加类型成功',$data);
        }catch (Exception $e){
            throw  $e;
        }
    }

    //删除商品
    public function delCom(Request $request,Commodity $commodity){
        $commodityId = $request->post('commodityId');
        if(!$commodity->delCom($commodityId)){
            return responseJson(Base::FAIL,'失败');
        }
        return responseJson(Base::OK,'成功');
    }
//搜索类型
    public function classSearch(Request $request ,Business $business,Commodity $commodity,CommodityClass $commodityClass){
        // TODO 将获取缓存信息放在中间件里
        $arr = $request->cacheInfo;
        $businessId = $arr["id"];//获取商家id
        $className = $request->post('commodityName');
        $time = $request->post('time');


        $classtext =json_decode($commodityClass->classSearch($businessId,$className),true);


        for ($i=0;$i<count($classtext);$i++){
            $classid = $classtext[$i]['id'];
            $classupdate = $classtext[$i]['updateTime'];
            $update =substr(date("Y-m-d H:i:s",$classupdate),0,10);
            $num = count(json_decode($commodity->findclasscom($businessId,$classid),true));

            $classtext[$i]['num']=$num;
            $classtext[$i]['updateTime']=$update;
        }

        if($time ==''){
            return  responseJson(Base::OK,$className.'列出成功',$classtext);
        }
        $array = array();
        for($q= 0;$q<count($classtext);$q++){
            $stime = $classtext[$q]['updateTime'];
            if($time == $stime){
                array_push($array,$classtext[$q]);
            }
        }
        return  responseJson(Base::OK,$className.'时间'.$time.'列出成功',$array);

    }
    public function delClass(Request $request,CommodityClass $commodityClass){
        $classId = $request->post('classId');
        if(!$commodityClass->updataClass($classId,'deleted',1)){
            return responseJson(Base::FAIL,'失败');
        }
        return responseJson(Base::OK,'成功');
    }
    public function infoClass(Request $request,CommodityClass $commodityClass){
        $classId = $request->post('classId');
        $name = $request->post('name');
        if($name ==""){
            return responseJson(Base::FAIL,'空？');
        }
        if(!$commodityClass->updataClass($classId,"catName",$name)){
            return responseJson(Base::FAIL,'失败');
        }
        return responseJson(Base::OK,'成功');
    }
}